package com.example.serviceorder.service.impl;

import com.example.order.Order;
import com.example.product.Product;
import com.example.serviceorder.feign.ProductFeignClient;
import com.example.serviceorder.service.OrderService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;


@Service
@Log4j2
public class OrderServiceImpl implements OrderService {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private ProductFeignClient productFeignClient;

    @Override
        public Order getOrderFromOpenFeignById(Long id){
        List<Product> productList = productFeignClient.getProductsByOrderId(id);
        Order order=new Order();
        BigDecimal totalAmount = new BigDecimal(0);
        for (Product product : productList) {
            totalAmount.add(product.getPrice().multiply(new BigDecimal(product.getNum())));
        }
        order.setTotalAmount(totalAmount);
        order.setId(1L);
        order.setUserId(10001L);
        order.setAddress("上海市浦东新区张江高科技园区");
        order.setProductList(productList);
        return order;
    }
    @Override
    public Order getProductsFromOpenFeignByIdSecure(Long id){
        List<Product> productList = productFeignClient.getProductsSecure(id, UUID.randomUUID().toString());
        Order order=new Order();
        BigDecimal totalAmount = new BigDecimal(0);
        for (Product product : productList) {
            totalAmount.add(product.getPrice().multiply(new BigDecimal(product.getNum())));
        }
        order.setTotalAmount(totalAmount);
        order.setId(1L);
        order.setUserId(10001L);
        order.setAddress("上海市浦东新区张江高科技园区");
        order.setProductList(productList);
        return order;
    }


    @Override
    public Order getOrderById(Long id) {
//        List<Product> productList = getProductFromRemoteByOrderId(id);
//        List<Product> productList = getProductFromRemoteWithLoadBalance(id);
        List<Product> productList = getProductFromRemoteWithLoadBalanceAnnotation(id);
        Order order=new Order();
        BigDecimal totalAmount = new BigDecimal(0);
        for (Product product : productList) {
            totalAmount.add(product.getPrice().multiply(new BigDecimal(product.getNum())));
        }
        order.setTotalAmount(totalAmount);
        order.setId(1L);
        order.setUserId(10001L);
        order.setAddress("上海市浦东新区张江高科技园区");
        order.setProductList(productList);
        return order;
    }

    /**
     * 方式一：
    **/
    private List<Product> getProductFromRemoteByOrderId(Long orderId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        if (instances.isEmpty()) {
            throw new RuntimeException("No available service-product instances");
        }

        ServiceInstance serviceInstance = instances.get(0);
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/product/" + orderId;
        System.out.println("请求URL: " + url);

        // 使用 exchange 方法配合 ParameterizedTypeReference 来获取泛型集合
        ResponseEntity<List<Product>> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<Product>>() {}
        );

        List<Product> products = response.getBody();
        System.out.println("收到的产品: " + products);
        return products;
    }

    /**
     * 方式二：完成负载均衡发送请求
    **/
    private List<Product> getProductFromRemoteWithLoadBalance(Long productId){
        //1、获取到商品服务所在的所有机器IP+port
        ServiceInstance choose = loadBalancerClient.choose("service-product");
        //远程URL
        String url = "http://"+choose.getHost() +":" +choose.getPort() +"/product/"+productId;
        log.info("远程请求：{}",url);
        //2、给远程发送请求
        // 使用 exchange 方法配合 ParameterizedTypeReference 来获取泛型集合
        ResponseEntity<List<Product>> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<Product>>() {}
        );

        List<Product> products = response.getBody();
        System.out.println("收到的产品: " + products);
        return products;
    }

    // 进阶3：基于注解的负载均衡
    private List<Product> getProductFromRemoteWithLoadBalanceAnnotation(Long productId){

        String url = "http://service-product/product/"+productId;
        // 给远程发送请求； service-product 会被动态替换
        // 使用 exchange 方法配合 ParameterizedTypeReference 来获取泛型集合
        ResponseEntity<List<Product>> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<Product>>() {}
        );

        List<Product> products = response.getBody();
        System.out.println("收到的产品: " + products);
        return products;
    }
}
